package com.jason.service;

import com.jason.exception.XDException;
import com.jason.mapper.*;
import com.jason.model.entity.Episode;
import com.jason.model.entity.PlayRecord;
import com.jason.model.entity.Video;
import com.jason.model.entity.VideoOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VideoOrderServceImpl implements VideoOrderServce{
    @Autowired
    private VideoOrderMapper videoOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private EpisodeMapper episodeMapper;
    @Autowired
    private PlayRecordMapper playRecordMapper;
    /**
     * 下单操作
     * 未来版本：优惠券抵扣，风控用户检测，生成订单基础信息。生成支付信息
     * @param userId
     * @param videoId
     * @return
     */
    @Override
    public int save(int userId, int videoId) {
        //判断是否已经购买
        VideoOrder videoOrder = videoOrderMapper.findByUserIdAndVideoIdAndState(userId, videoId, 1);
        if (videoOrder != null) {
            return 0;
        }
        Video video = videoMapper.findById(videoId);
        VideoOrder videoOrder1 = new VideoOrder();
        videoOrder1.setCreateTime(new Date());
        videoOrder1.setOutTradeNo(UUID.randomUUID().toString());
        videoOrder1.setState(1);
        videoOrder1.setTotalFee(video.getPrice());
        videoOrder1.setUserId(userId);
        videoOrder1.setVideoId(videoId);
        videoOrder1.setVideoImg(video.getCoverImg());
        videoOrder1.setVideoTitle(video.getTitle());
        int rows = videoOrderMapper.saveOrder(videoOrder1);
        
        //生成播放记录
        if(rows==1){
            Episode episode=episodeMapper.findFirstEpisodeByVideoId(videoId);
            if (episode==null){
                throw new XDException(-1,"视频没有集信息，请运营人员检查");
            }
            PlayRecord playRecord=new PlayRecord();
            playRecord.setCreateTime(new Date());
            playRecord.setEpisodeId(episode.getId());
            playRecord.setCurrentNum(episode.getNum());
            playRecord.setUserId(userId);
            playRecord.setVideoId(videoId);
            playRecordMapper.saveRecord(playRecord);
        }
        return rows;
    }

    @Override
    public List<VideoOrder> listOrderByUserId(Integer userId) {
        return videoOrderMapper.listOrderByUserId(userId);
    }
}
